package com.programmercarl.stackandqueue;

import java.util.*;

/**
 * https://leetcode.cn/problems/top-k-frequent-elements/description/
 *
 * @author yulongtian
 * @create 2024-12-16 14:00
 */
public class Test04 {
    public static void main(String[] args) {
//        System.out.println(Arrays.toString(topKFrequent(new int[]{1, 1, 3, 3, 3, 1, 2, 2, 3}, 2)));
        System.out.println(Arrays.toString(topKFrequent(new int[]{1, 2}, 2)));
    }

    public static int[] topKFrequent(int[] nums, int k) {
        Arrays.sort(nums);
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
        }
        int[] temp = new int[map.size()];
        int i = 0;

        HashMap<Integer, Integer> map_temp = new HashMap<>();
        for (Integer key : map.keySet()) {
            temp[i++] = map.get(key);
            map_temp.put(map.get(key), key);
        }

        Arrays.sort(temp);
        int[] res = new int[k];
        for (int j = temp.length - 1, index = 0; index < k; j--) {
            res[index++] = map_temp.get(temp[j]);
        }

        return res;
    }

}
